package com.photoeditor.demo.ui.adapter.gallery;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.imageloader.GlideApp;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.bean.ImageFolder;
import com.photoeditor.demo.ui.activity.GalleryActivity;
import com.photoeditor.demo.ui.fragement.gallery.OtherGalleryFragment;
import com.photoeditor.demo.util.FontUtil;
import com.photoeditor.demo.util.ImageManageUtil;
import com.photoeditor.demo.util.MediaFile;

import java.util.ArrayList;


public class FolderListAdapter extends ArrayAdapter<ImageFolder> {

    private GalleryActivity mActivity;

    private ArrayList<ImageFolder> mData;

    private LayoutInflater mInfl;

    //当前是不是选中状态
    private boolean isCheckStatus;

    private int mColNum;

    private int mImageWidth;

    private int mTextHeight;

    //用于回调
    private ICheckedChangeListener mListener;

    private IModeChangeListener mModeChangeListener;

    private ArrayList<ImageFolder> mCheckList;

    /**
     * 两张图片之间的间距
     */
    private int mMargin;
    private int mLefMargin;
    private Drawable mItemShapeDrawable;

    public FolderListAdapter(GalleryActivity context, ArrayList<ImageFolder> data, int cNum) {
        super(context, 0, data);
        this.mActivity = context;
        this.mData = data;
        mInfl = LayoutInflater.from(mActivity);
        mCheckList = new MyArrayList<>();
        isCheckStatus = false;
        mColNum = cNum;
        Resources res = context.getResources();
        mMargin = res.getDimensionPixelSize(R.dimen.gallery_distance);
        mLefMargin = res.getDimensionPixelSize(R.dimen.gallery_left_margin);
        mImageWidth = (ImageManageUtil.getScreenWidth() - (mColNum - 1) * mMargin - mLefMargin * 2) / mColNum;
        mTextHeight = DeviceUtils.dip2px(mActivity, 40.5f);
        mItemShapeDrawable = res.getDrawable(R.drawable.gallery_floder_bg_shape);
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public ImageFolder getItem(int position) {
        if (position < mData.size()) {
            return mData.get(position);
        }
        return null;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInfl.inflate(R.layout.item_folder, null);
            LayoutParams lp = new LayoutParams(mImageWidth, mImageWidth + mTextHeight);
            convertView.setLayoutParams(lp);
            holder.layout = convertView.findViewById(R.id.image_layout);
            holder.image = (ImageView) convertView.findViewById(R.id.iv);
//            holder.image.setShapeDrawable(mItemShapeDrawable);
            //holder.image.setRadius(DeviceUtils.dip2px(convertView.getContext(), 5));
            holder.mask = (ImageView) convertView.findViewById(R.id.mask);
            //holder.mask.setRadius(DeviceUtils.dip2px(convertView.getContext(), 5));
            holder.check = (CheckBox) convertView.findViewById(R.id.check_box);
            holder.name = (TextView) convertView.findViewById(R.id.name);
            holder.num = (TextView) convertView.findViewById(R.id.num);
            FontUtil.setCustomFont(holder.name, holder.num);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final ImageFolder bean = mData.get(position);
        holder.layout.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                if (mActivity.isPickMode()) {

                } else {
                    if (!isCheckStatus) {
                        bean.setChecked(!isCheckStatus);
                        mCheckList.add(bean);
                        setCheckStatus(!isCheckStatus);
                    }
                }
                return true;
            }
        });
        holder.layout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isCheckStatus) {
                    bean.setChecked(!bean.isChecked());
                    CheckBox check = (CheckBox) v.findViewById(R.id.check_box);
                    check.setVisibility(View.VISIBLE);
                    check.setChecked(bean.isChecked());
                    View mask = v.findViewById(R.id.mask);
                    mask.setVisibility(bean.isChecked() ? View.VISIBLE : View.GONE);
                    if (bean.isChecked()) {
                        mCheckList.add(bean);
                    } else {
                        mCheckList.remove(bean);
                    }
                } else {
                    mModeChangeListener.onModeChange(OtherGalleryFragment.MODE_GALLERY, position);
                }
            }
        });

        if (isCheckStatus) {
            holder.check.setVisibility(View.VISIBLE);
            boolean checked = bean.isChecked();
            holder.check.setChecked(checked);
            holder.mask.setVisibility(checked ? View.VISIBLE : View.GONE);
        } else {
            holder.check.setVisibility(View.GONE);
            holder.mask.setVisibility(View.GONE);
        }
        holder.name.setText(bean.getName());
        holder.num.setText("(" + bean.getCount() + ")");

        String path = bean.getFirstThumbnailBean().getPath();
        if (MediaFile.getFileType(path) != null && MediaFile.isVideoFileType(MediaFile.getFileType(path).fileType)) {
            GlideApp.with((Activity) getContext()).load(path)
                    .placeholder(R.drawable.ic_default_image).into(holder.image);
        } else {///storage/emulated/0/DCIM/Camera/DYNAMIC_20170920_094848250.mp4
            //ImageLoader.loadImage((Activity) getContext(), Uri.parse(path).toString(), R.drawable.ic_default_image, holder.image);
            GlideApp.with((Activity) getContext())
                    .asBitmap()
                    .load(Uri.parse(path).toString())
                    .placeholder(R.drawable.ic_default_image)
                    .into(holder.image);
            ImageLoader.loadImage((Activity) getContext(), Uri.parse(path).toString(), R.drawable.ic_default_image, holder.image);
//        FetcherHolder.getSmallImageFetcher().loadImage(bean.getFirstThumbnailBean().getPath(), bean.getFirstThumbnailBean().getDegree(), holder.image, true);
        }
        return convertView;
    }


    @Override
    public boolean isEmpty() {
        if (mData == null || mData.size() == 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isEnabled(int position) {
        return super.isEnabled(position);
    }

    public void setData(ArrayList<ImageFolder> data) {
        this.mData = data;
        notifyDataSetChanged();
    }

    /**
     * 用于ArrayAdapter中getView的缓存
     */
    public static class ViewHolder {
        View layout;
        ImageView image;
        ImageView mask;
        CheckBox check;
        TextView name;
        TextView num;
    }

    /**
     * 设置当前是选中状态还是非选中状态
     *
     * @param checkStatus
     */
    public void setCheckStatus(boolean checkStatus) {
        if (checkStatus != this.isCheckStatus) {
            this.isCheckStatus = checkStatus;
            if (!isCheckStatus) {
                restoreCheckedList();
            }
            if (mListener != null) {
                mListener.onCheckedStatusChange(isCheckStatus);
            }
            notifyDataSetChanged();
        }
    }

    public void restoreCheckedList() {
        int len = mCheckList.size();
        for (int i = 0; i < len; i++) {
            mCheckList.get(i).setChecked(false);
        }
        mCheckList.clear();
    }

    public void clearCheckedList() {
        mCheckList.clear();
    }

    public void setOnCheckedChangeListener(ICheckedChangeListener l) {
        mListener = l;
    }

    public void setOnModeChangeListener(IModeChangeListener l) {
        mModeChangeListener = l;
    }

    public boolean isCheckStatus() {
        return isCheckStatus;
    }

    /**
     * 获取当前选中的list  深度复制
     *
     * @return
     */
    public ArrayList<ImageFolder> getCheckedList() {
        ArrayList<ImageFolder> result = new ArrayList<ImageFolder>();
        int l = mCheckList.size();
        for (int i = 0; i < l; i++) {
            result.add(mCheckList.get(i));
        }
        return result;
    }

    /**
     * 全选或者全不选
     *
     * @param checked
     */
    public void checkAll(boolean checked) {
        if (mData == null) return;
        if (checked) {
            int len = mData.size();
            for (int i = 0; i < len; i++) {
                ImageFolder bean = mData.get(i);
                if (!bean.isChecked()) {
                    bean.setChecked(true);
                    mCheckList.add(bean);
                }
            }
        } else {
            restoreCheckedList();
        }
        notifyDataSetChanged();
    }

    //继承ArrayList用于回调数目
    class MyArrayList<ImageFolder> extends ArrayList<ImageFolder> {
        @Override
        public boolean remove(Object object) {
            boolean result = super.remove(object);
            if (mListener != null) {
                mListener.onCheckedNumChange(false, size());
            }
            return result;
        }

        @Override
        public boolean add(ImageFolder object) {
            boolean result = super.add(object);
            if (mListener != null) {
                mListener.onCheckedNumChange(false, size());
                if (size() == mData.size()) {
                    mListener.onAllCheckedChange(true);
                }
            }
            return result;
        }

        @Override
        public void clear() {
            super.clear();
            if (mListener != null) {
                mListener.onCheckedNumChange(false, size());
            }
        }

        /**
         * @param flag
         */
        public void clear(boolean flag) {
            super.clear();
            if (flag) {
                if (mListener != null) {
                    mListener.onCheckedNumChange(false, size());
                }
            }
        }
    }
}
